package objpool

import (
	"errors"
	"time"
)

// 演示对象池
type BigObj struct {
	name string
}

type ObjPool struct {
	bufchan chan *BigObj
}

// 初始化一个pool
func NewObjPool(num int) *ObjPool {
	objPool := ObjPool{}
	// 核心就是一个缓存长度为num的chan
	objPool.bufchan = make(chan *BigObj, num)
	for i := 0; i < num; i++ {
		objPool.bufchan <- &BigObj{"bigThing"}
	}
	return &objPool
}

// 加一个超时时间
func (pool *ObjPool) GetOneObj(timeout time.Duration) (*BigObj, error) {
	select {
	case res := <-pool.bufchan:
		return res, nil
	case <-time.After(timeout):
		return nil, errors.New("pool empty")
	}
}

func (pool *ObjPool) GiveBackOneObj(obj *BigObj, timeout time.Duration) error {
	select {
	case pool.bufchan <- obj:
		return nil
	case <-time.After(timeout):
		return errors.New("pool full")
	}
}
